/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controller;

import DataAccess.DataAccessFacade;
import DomainModel.Role;
import DomainModel.Section;
import DomainModel.User;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.json.JSONArray;
import org.json.JSONObject;

/**
 *
 * @author Patrick
 */
public class AdminEnrollController extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        //PrintWriter out = response.getWriter();
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("currentUser");

        if (user == null || user.getRole() != Role.ADMIN) {
            request.getRequestDispatcher("/login").forward(request, response);
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);

//        String strSectionId = request.getParameter("inputSectionId");
//        String strSectionId2 = request.getParameter("sectionId");
//        String strSectionId3 = request.getParameter("sid");

        String action = request.getParameter("action");

        if (action != null && action.equals("loadStudents")) {

            doLoadStudents(request, response);
        } else {
            loadSection(request, Integer.parseInt(request.getParameter("sid")));
        }

        request.getRequestDispatcher("/WEB-INF/grs/adminSectionsEnroll.jsp").forward(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);

        String action = request.getParameter("action");
        String backToSections = request.getParameter("backToSections");
        String enrollStudents = request.getParameter("enrollStudents");
        
        if (enrollStudents != null) {
            doEnrollSection(request, response);
            request.getRequestDispatcher("/WEB-INF/grs/adminSectionsView.jsp").forward(request, response);
        } //return to adminSectionsView
        else if (backToSections != null) {
            response.sendRedirect("adminSections");
        } else {
            String inputSectionId = request.getParameter("inputSectionId").toString();
            try {
                List<User> sectionStudents = DataAccessFacade.getInstance().getSectionStudents(Integer.valueOf(inputSectionId));
                request.setAttribute("sectionStudents", sectionStudents);
            } catch (Exception ex) {
                Logger.getLogger(AdminSectionController.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    protected void doLoadStudents(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            DataAccessFacade daf = DataAccessFacade.getInstance();

            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            try {
                List<User> allStudents = daf.getAllStudents();
                request.setAttribute("studentList", allStudents);
                JSONArray allStudentsJson = new JSONArray();

                for (User student : allStudents) {

                    JSONObject studentJson = new JSONObject();

                    studentJson.put("UserId", student.getUserId());
                    studentJson.put("FirstName", student.getFirstName());
                    studentJson.put("LastName", student.getLastName());
                    studentJson.put("Username", student.getUsername());
                    studentJson.put("Email", student.getEmail());

                    allStudentsJson.put(studentJson);
                }
                String allStudentsStr = allStudentsJson.toString();
                out.print(allStudentsStr);

            } catch (Exception e) {
            } finally {
                out.close();
            }
        } catch (Exception e) {
        }
    }

    private boolean doEnrollSection(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        List<User> studentList = (List<User>) request.getAttribute("studentList");
        Map<String, String> messages = new HashMap<>();
        request.setAttribute("messages", messages);
  
        try {
            List<Integer> studentIdList = convertStringArrayToIntArray(request.getParameterValues("inputUserId"));         
            int sectionId = Integer.parseInt(request.getParameter("inputSectionId"));
            DataAccessFacade.getInstance().setSectionStudents(sectionId, studentIdList);
            messages.put("success", "Students enrolled successfully.");
        } catch (Exception e) {
            messages.put("error", "An error occurred enrolling students in this section.");
            return false;
        }
        return true;
    }

    private void loadSection(HttpServletRequest request, int sectionId) {
        try {
            request.setAttribute("inputSectionId", sectionId);
            Section section = DataAccessFacade.getInstance().getSectionById(sectionId);
            request.setAttribute("section", section);
        } catch (Exception e) {
          }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private List<Integer> convertStringArrayToIntArray(String[] strArray) {
        List<Integer> intArray = new ArrayList<>();

        for (int i = 0; i < strArray.length; i++) {
            intArray.add(Integer.parseInt(strArray[i]));
        }

        return intArray;
    }
}
